﻿using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ConsoleApp1
{
    internal class Program
    { 

        static void Main(string[] args)
        {
            Console.WriteLine("开始监听显示器状态...");

            bool lastState = true; // 假设初始为开

            while (true)
            {
                bool isOn = IsScreenOn();
                if (isOn != lastState)
                {
                    lastState = isOn;
                    Console.WriteLine(isOn ? "显示器已开启" : "显示器已关闭/息屏");
                }
                Thread.Sleep(1000); // 每秒轮询一次
            }
        }
        static bool IsScreenOn()
        {
            try
            {
                // 获取屏幕中央像素的颜色
                int x = Screen.PrimaryScreen.Bounds.Width / 2;
                int y = Screen.PrimaryScreen.Bounds.Height / 2;

                using (Bitmap bmp = new Bitmap(1, 1))
                {
                    using (Graphics g = Graphics.FromImage(bmp))
                    {
                        g.CopyFromScreen(x, y, 0, 0, new Size(1, 1));
                    }
                    Color c = bmp.GetPixel(0, 0);
                    // 如果像素接近黑色，认为屏幕关闭

                    Console.WriteLine($"中央像素颜色: R={c.R}, G={c.G}, B={c.B}");
                    return c.R + c.G + c.B > 30;
                }
            }
            catch
            {
                return true; // 出错时默认显示器开启
            }
        }
    }
}
